{% include "data/template-ui.html" %}
<script src="/static/js/components/modal.js"></script>
<link rel="stylesheet" href='/static/zTree/css/zTreeStyle.css'>
<link rel="stylesheet" type="text/css" href="/static/css/sweetalert.css"/>

<style>
    .page-body {
        flex: 1;
        height: 0;
        overflow: auto;
        padding: 10px 15px;
    }
    #std td {
        font-size: 15px;
        color: black !important;
        text-align: left !important;
        vertical-align: top;
        width: 15px;
        padding-top: 10px;
    }

    #desc {
        white-space: pre-wrap;
        color: black !important;
        line-height: 30px;
    }

    #key {
        width: 240px;
        margin-left: 30px;
        height: 30px;
        font-size: 14px;
    }
    #treeDemo {
        margin: 10px 0;
    }
</style>

<!-- 正文主体 -->
<div class="container-fluid animated fadeInUp">
    <div class="row page-titles">
        <div class="col-md-12 align-self-center">
            <h3 class="text-primary">数据标准</h3>
        </div>
    </div>

    <div class="page-body">
        <div class="row" style="height: 100%;">
            <div class="col-md-3">
                <div class="card" style="height: 100%;margin: 0;">
                    <div class="row" style="margin-bottom: 12px;">
                        <button class="btn btn-primary btn-sm" onclick="addFolder()" style="margin-left: 10px;">新增目录
                        </button>
                        <button class="btn btn-primary btn-sm" onclick="addFile()" style="margin-left: 10px;">新增文件
                        </button>
                    </div>
                    <div class="row">
                        <h5 style="line-height: 30px;margin-bottom: 0;color:black;font-weight:600;">目录</h5>
                        <input type="text" id="key" value="" class="empty form-control" placeholder="搜索关键字" autocomplete="off"/>
                    </div>
                    <ul id="treeDemo" class="ztree"></ul>
                </div>
            </div>

            <div class="col-md-9" style="padding-left: 0;">
                <div class="card" onload="FristLoad();" style="height: 100%;margin: 0;">
                    <!-- 标准标题 -->
                    <div class="row">
                        <div class="col-md-10">
                            <h3 style="color:black;font-weight:600;" id="desc_name"></h3>
                            <!--<input id="desc_name" class="form-control" type="text" value="" autocomplete="off" style="width: 400px;">-->
                        </div>

                        <div class="col-md-2 pull-right">
                            <button id="save_btn" class="btn btn-primary btn-sm" onclick="save()">保 存</button>
                        </div>
                    </div>

                    <!-- 标准概述 -->
                    <textarea id="desc_content" class="form-control" type="text" value=""
                              style="height: 600px;margin-top: 20px;"></textarea>

                </div>
            </div>

        </div>
    </div>
</div>
</div>

<script src='/static/zTree/js/jquery.ztree.core.min.js'></script>
<script src='/static/zTree/js/fuzzysearch.js'></script>
<script src='/static/zTree/js/jquery.ztree.exhide.min.js'></script>
<script src='/static/zTree/js/jquery.ztree.exedit.js'></script>
<script type="text/javascript" src="/static/js/sweetalert.min.js"></script>

<SCRIPT type="text/javascript">
    var setting = {
        view: {
            // addHoverDom: addHoverDom,
            removeHoverDom: removeHoverDom,
            selectedMulti: false
        },
        edit: {
            enable: true,
            editNameSelectAll: true
        },
        data: {
            key: {
                title:"t"
            },
            simpleData: {
                enable: true
            }
        },
        callback: {
            beforeClick: beforeClick,
            onClick: onClick,
            beforeDrag: beforeDrag,
            beforeEditName: beforeEditName,
            beforeRemove: beforeRemove,
            beforeRename: beforeRename,
            onRename: onRename
        },
        // async: {
        //     enable: true,
        //     url:"../../api/datastandard/query/index",
        //     autoParam:["id", "pId", , "pk_id", "name", "t", "open"],
        //     type: "get",
        //     //otherParam:{"otherParam":"zTreeAsyncTest"},
        //     // dataFilter: filter
        // },
    };

    var log, className = "dark", newCount = 1, curSelectedNode = null;

    function beforeDrag(treeId, treeNodes) {
        return false;
    }
    function beforeClick(treeId, treeNode, clickFlag) {
        curSelectedNode = treeNode;
        className = (className === "dark" ? "":"dark");
        showLog("[ "+getTime()+" beforeClick ]&nbsp;&nbsp;" + treeNode.name );
        return (treeNode.click != false);
    }
    function onClick(event, treeId, treeNode, clickFlag) {
        $('#desc_name').html(treeNode.name);
        if (treeNode.isParent) {    // 文件夹则不发起请求
            $('#desc_content').val('');
            return;
        }

        $.ajax({
            type : "GET",
            async : false,
            url : "../../api/datastandard/query/detail",
            data: {
                index_id: treeNode.pk_id,
                std_type: "desc"        //标准概述
            },
            dataType : "json",
            success : function(result) {
                $('#desc_content').val(result.content);
            },
        });
    }
    function showLog(str) {
        if (!log) log = $("#log");
        log.append("<li class='"+className+"'>"+str+"</li>");
        if(log.children("li").length > 8) {
            log.get(0).removeChild(log.children("li")[0]);
        }
    }
    function getTime() {
        var now= new Date(),
        h=now.getHours(),
        m=now.getMinutes(),
        s=now.getSeconds();
        return (h+":"+m+":"+s);
    }

    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
            + "' title='add node' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_" + treeNode.tId);
        if (btn) btn.bind("click", function () {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo");
            zTree.addNodes(treeNode, {
                isParent: true,
                id: (100 + newCount),
                pId: treeNode.id,
                name: "new node" + (newCount++)
            });
            return false;
        });
    }

    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_" + treeNode.tId).unbind().remove();
    }

    function beforeEditName(treeId, treeNode) {
        className = (className === "dark" ? "" : "dark");
        showLog("[ " + getTime() + " beforeEditName ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        zTree.selectNode(treeNode);
        setTimeout(function () {
            zTree.editName(treeNode);
        }, 0);
        return false;
    }

    function beforeRemove(treeId, treeNode) {
        className = (className === "dark" ? "" : "dark");
        showLog("[ " + getTime() + " beforeRemove ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name);
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        zTree.selectNode(treeNode);
        swal({
            title: "操作确认",
            text: "删除后，您将无法恢复此文件！",
            icon: "warning",
            cancelButtonText: '确定',
            buttons: {
                cancel: {
                    text: "取消",
                    visible: true,
                },
                confirm: {
                    text: "确定",
                }
            },
            dangerMode: true,
        }).then(e => {
            if (e) {
                removeNode(zTree, treeNode);
            }
        });
        return false;
    }

    function removeNode(zTree, treeNode) {
        $.ajax({
            type: "POST",
            contentType: 'application/json',
            url: "../../api/datastandard/delete/index",
            data: JSON.stringify({
                id: treeNode.id,
                pk_id: treeNode.pk_id
            }),
            success: function (result) {
                if (result.stat === 200) {
                    if (curSelectedNode && curSelectedNode.id == treeNode.id) {
                        $('#desc_name').html('');
                        $('#desc_content').val('');
                    }
                    curSelectedNode = null; // 删除成功后，重置为null
                    zTree.removeNode(treeNode);

                    let parentNode = treeNode.getParentNode();
                    if(!parentNode.isParent) {
                        parentNode.isParent = true;
                        parentNode.open = true;
                        zTree.updateNode(parentNode);
                    }
                } else {
                    swal({
                        title: '删除失败！',
                        text: result.msg,
                        icon: "error",
                    });
                }
            }
        });
    }

    function beforeRename(treeId, treeNode, newName, isCancel) {
        className = (className === "dark" ? "" : "dark");
        showLog((isCancel ? "<span style='color:red'>" : "") + "[ " + getTime() + " beforeRename ]&nbsp;&nbsp;&nbsp;&nbsp; " + treeNode.name + (isCancel ? "</span>" : ""));
        if (newName.length == 0) {
            setTimeout(function () {
                var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                zTree.cancelEditName();
                alert("节点名称不能为空.");
            }, 0);
            return false;
        }
        return true;
    }

    function onRename(e, treeId, treeNode, isCancel) {
        curSelectedNode = treeNode;
        if (!isCancel) {
            $.ajax({
                type: "POST",
                contentType: 'application/json',
                url: "../../api/datastandard/update/index",
                data: JSON.stringify({
                    pk_id: treeNode.pk_id,
                    pId: treeNode.pId || 0,
                    open: treeNode.open,
                    name: treeNode.name
                }),
                success: function (result) {
                    if (result.stat == 200) {
                        $('#desc_name').html(treeNode.name);
                    } else {
                        swal({
                            title: '重命名失败！',
                            text: result.msg,
                            icon: "error",
                        });
                    }
                }
            });
        }
    }

    function addFolder() {
        let zTree = $.fn.zTree.getZTreeObj("treeDemo");
        let { pId, pNode } = getParent(zTree, curSelectedNode);
        $.ajax({
            type: "POST",
            contentType: 'application/json',
            url: "../../api/datastandard/add/index",
            data: JSON.stringify({
                pId: pId,
                is_dir: true,
                open: true,
                name: "新建文件夹"
            }),
            success: function (result) {
                if (result.stat === 200) {
                    $('#desc_content').val('');
                    zTree.addNodes(pNode, {isParent: true, id: result.data[0].id, pId: 0, pk_id: result.data[0].pk_id, name: "新建文件夹"});
                    if (pNode) {
                        zTree.editName(pNode.children[pNode.children.length - 1]);
                    } else {
                        let nodes = zTree.getNodes();
                        zTree.editName(nodes[nodes.length - 1]);
                    }
                } else {
                    swal({
                        title: '新建文件夹失败！',
                        text: result.msg,
                        icon: "error",
                    });
                }
            }
        });
    }

    function addFile() {
        let zTree = $.fn.zTree.getZTreeObj("treeDemo");
        let { pId, pNode } = getParent(zTree, curSelectedNode);
        $.ajax({
            type: "POST",
            contentType: 'application/json',
            url: "../../api/datastandard/add/index",
            data: JSON.stringify({
                pId: pId,
                is_dir: false,
                open: true,
                name: "新建文件"
            }),
            success: function (result) {
                if (result.stat === 200) {
                    $('#desc_content').val('');
                    zTree.addNodes(pNode, {isParent: false, id: result.data[0].id, pId: 0, pk_id: result.data[0].pk_id, name: "新建文件"});
                    if (pNode) {
                        zTree.editName(pNode.children[pNode.children.length - 1]);
                    } else {
                        let nodes = zTree.getNodes();
                        zTree.editName(nodes[nodes.length - 1]);
                    }
                } else {
                    swal({
                        title: '新建文件失败！',
                        text: result.msg,
                        icon: "error",
                    });
                }
            }
        });
    }

    function getParent(zTree, curNode) {
        if (!curNode) { // 未选中
            return { pId: 0, pNode: null };
        } else if (curNode.isParent) { // 文件夹，取自身id
            return { pId: curNode.id || 0, pNode: zTree.getSelectedNodes()[0] };
        } else { // 文件，则取父目录id
            if (curNode.pId == null) {
                return { pId: 0, pNode: null };
            } else {
                return { pId: curNode.getParentNode().id, pNode: curNode.getParentNode() };
            }
        }
    }

    function save() {
        if (!curSelectedNode) return;   // 没有选中文件 无法保存

        let titleEdit = $('#desc_name');
        let contentEdit = $('#desc_content');

        $.ajax({
            type: "POST",
            url: "../../api/datastandard/update",
            contentType: 'application/json',
            data: JSON.stringify({
                username : "{{ username }}",
                index_id: curSelectedNode.pk_id,
                pId: curSelectedNode.pId,
                std_type : 'desc',
                std_name : titleEdit.html(),
                content  : contentEdit.val()
            }),
            success: function (data) {
                if (data.stat == 200) {
                    let treeNode = $(`#treeDemo [title=${curSelectedNode.name}]`);
                    treeNode.attr('title', titleEdit.val());
                    treeNode.find('.node_name').html(titleEdit.val());
                    swal({
                        title: '保存成功！',
                        text: data.msg,
                        icon: "success",
                    });
                } else {
                    swal({
                        title: '保存失败！',
                        text: data.msg,
                        icon: "error",
                    });
                }
            },
            error: function (e) {
                swal({
                    title: "发生错误",
                    text: e,
                    icon: "error",
                })
            }
        })
    }

    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: "../../api/datastandard/query/index",
            dataType: "json",
            success: function (result) {
                if (result.stat === 200) {
                    result.data.forEach(v => {
                        v.isParent = v.is_dir;
                    });
                    $.fn.zTree.init($("#treeDemo"), setting, result.data);
                    fuzzySearch('treeDemo', '#key', null, null);           //初始化模糊搜索方法
                }
            }
        });
    });
</SCRIPT>
</body>

</html>